﻿using System;
using System.IO;
using System.Windows;
using Flux.Editor.Extensions;
using Microsoft.Win32;

namespace Flux.Editor.Dialogs
{
	public partial class NewTilesetDialog
	{
		public string TilesetName { get; set; }
		public string ImagePath { get; set; }
		public int TileWidth { get; set; }
		public int TileHeight { get; set; }

		public NewTilesetDialog()
		{
			InitializeComponent();

			if (App.Project != null)
			{
				txtTileWidth.Text = App.Project.TileWidth.ToString();
				txtTileHeight.Text = App.Project.TileHeight.ToString();
			}
		}

		private void BtnOk_OnClick(object sender, RoutedEventArgs e)
		{
			if (string.IsNullOrEmpty(txtImagePath.Text))
			{
				MessageBox.Show("Tileset needs a specified image.");
				return;
			}

			if (string.IsNullOrEmpty(txtName.Text))
			{
				MessageBox.Show("Tileset needs a specified name.");
				return;
			}

			if (!txtTileWidth.Text.IsNumeric())
			{
				MessageBox.Show("Width needs to be numeric");
				return;
			}

			if (!txtTileHeight.Text.IsNumeric())
			{
				MessageBox.Show("Height needs to be numeric");
				return;
			}

			if (!File.Exists(txtImagePath.Text))
			{
				MessageBox.Show("Specified image path doesn't exist.");
				return;
			}

			ImagePath = txtImagePath.Text;
			TilesetName = txtName.Text;
			TileWidth = Convert.ToInt32(txtTileWidth.Text);
			TileHeight = Convert.ToInt32(txtTileHeight.Text);

			DialogResult = true;
		}

		private void BtnCancel_OnClick(object sender, RoutedEventArgs e)
		{
			DialogResult = false;
		}

		private void BtnImagePathLookup_OnClick(object sender, RoutedEventArgs e)
		{
			var dialog = new OpenFileDialog
			{
				Filter = "Image Files (*.bmp;*.jpg;*.jpeg;*.png)|*.bmp;*.jpg;*.jpeg;*.png|BMP (*.bmp)|*.bmp|JPEG (*.jpg; *.jpeg)|*.jpg;*.jpeg|PNG (*.png)|*.png|All files (*.*)|*.*"
			};
			var results = dialog.ShowDialog();
			if (results == true)
			{
				var filename = dialog.FileName;
				txtImagePath.Text = filename;
				txtName.Text = Path.GetFileNameWithoutExtension(filename);
			}
		}
	}
}
